
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;

import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.sales.ContactPerson;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.SendAckMailForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;


public class SendAckMailAction extends ChipTrackAction
{
    public SendAckMailAction () { }

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response )
    {

        HashMap info = new HashMap ();
        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        HashMap errors = new HashMap ();
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        SendAckMailForm sendAckMailForm = ( SendAckMailForm ) form;
        String salesOrderId = request.getParameter ( "salesOrderId" );
        String showAgain = request.getParameter ( "showAgain" );
        SalesOrder salesOrder = null;
        boolean success = false;
        String action = request.getParameter ( "action" );

        request.setAttribute ( "salesOrderId", salesOrderId );
        request.setAttribute( "showAgain", showAgain );
        
        int externalUserEmailsLength = 0;
        String customerPO = null;
        String customerName = null;
        ArrayList contactPersons = null;
        String types[] = null;

        String subject = null;
        String[] toUsers = null;
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        try
        {
            if ( salesOrderId != null )
            {
                salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId );
                customerPO = salesOrder.getCustomerPO ();
                customerName = salesOrder.getCustomerName ();
            }
        }
        catch ( ScalarException se )
        {
            System.out.println ( "Exception while loading sales order No..... " );
            se.getRootCause ().printStackTrace ();
        }

        String mimeType = sendAckMailForm.getAttachMIMEType ();

        if ( ( mimeType == null ) || ( mimeType.trim ().length () == 0 ) )
        {
            mimeType = "PDF";
            sendAckMailForm.setAttachMIMEType ( "PDF" );
        }


        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/sendAckMail.do?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }
        //String from = user.getEmail ();

        if ( ( action != null ) && ( action.equalsIgnoreCase ( "save" ) ) )
        {
            try
            {
                String to = StringUtils.concatStrings ( sendAckMailForm.getToUsers (), Mailer.EMAIL_SEPARATOR );
                String cc = StringUtils.concatStrings ( sendAckMailForm.getCcUsers (), Mailer.EMAIL_SEPARATOR );
                String bcc = StringUtils.concatStrings ( sendAckMailForm.getBccUsers (), Mailer.EMAIL_SEPARATOR );

                to = Mailer.getNotifiableEmails ( to, false );
                cc = Mailer.getNotifiableEmails ( cc, false );
                bcc = Mailer.getNotifiableEmails ( bcc, false );

                if ( cc == null )
                {
                    sendAckMailForm.setCcUsers ( null );
                }
                if ( bcc == null )
                {
                    sendAckMailForm.setBccUsers ( null );
                }
                subject = sendAckMailForm.getSubject ();

                if ( subject == null )
                {
                    int orderType = request.getParameter("isSample") == null ? 1 : Integer.parseInt( request.getParameter("isSample") );
                    if ( orderType == 0 )
                    {
                        subject = "Sample SalesOrder Acknowledgement for "+ salesOrder.getSalesOrderNo();
                    }
                    else {
                        subject = " Sales Order Acknowledgement for : " + customerPO;
                    }
                }
                sendAckMailForm.setSubject ( subject );

                String message = sendAckMailForm.getMessage ().replaceAll( "\n", "<br>" );

                String host = request.getHeader ( "HOST" );

                String salesAckFile = null;

                String[] mailAttachments = null;

                String isConfirm = ( String ) session.getAttribute ( "isConfirm" );
                String sysAdminEmail = ConfigManager.getSysAdminEmail ();
                String companyEmailId = sysAdminEmail.substring ( sysAdminEmail.indexOf ( "@" ) + 1, sysAdminEmail.length () );
                if ( isConfirm == null )
                {
                    to = Mailer.getNotifiableEmails ( to, false );
                    cc = Mailer.getNotifiableEmails ( cc, false );
                    bcc = Mailer.getNotifiableEmails ( bcc, false );
                    InternetAddress[] toAddress = null;
                    InternetAddress[] ccAddress = null;
                    InternetAddress[] bccAddress = null;

                    String emailIds = "";
                    if ( to != null )
                    {
                        toAddress = InternetAddress.parse ( to );
                        for ( int i = 0; i < toAddress.length; i++ )
                        {
                            InternetAddress temp = toAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                 emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }
                    if ( cc != null )
                    {
                        ccAddress = InternetAddress.parse ( cc );
                        for ( int i = 0; i < ccAddress.length; i++ )
                        {
                            InternetAddress temp = ccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                    emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                    emailIds = emailIds +", "+ temp.getAddress () ;
                                }

                            }
                        }
                    }
                    if ( bcc != null )
                    {
                        bccAddress = InternetAddress.parse ( bcc );
                        for ( int i = 0; i < bccAddress.length; i++ )
                        {
                            InternetAddress temp = bccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                    emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                    emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }

                    if ( emailIds.trim ().length () > 0 )
                    {
                        errors.put ( "The following e-mails are going out of the company. Please confirm to send them.", null );
                        info.put ( "Emails ", emailIds );

                        session.setAttribute ( "isConfirm", "True" );
                        return mapping.findForward ( "success" );
                    }

                }

                if ( "PDF".equalsIgnoreCase ( mimeType ) )
                    salesAckFile = OrderAction.getSalesAckPDFFile ( host, salesOrderId );
                else
                    salesAckFile = OrderAction.getsalesAckHtmlFile ( host, salesOrderId );

                mailAttachments = new String[]{salesAckFile};
                Mailer.send (  sendAckMailForm.getFromUser() , to, cc, bcc, subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
                info.put ( "Email has been sent successfully", null );
                session.removeAttribute ( "ShowAgain" );
                session.removeAttribute ( "isConfirm" );
            }
            catch ( Exception se )
            {
                success = false;
                String errMessage = "Error";
                errors.put ( errMessage, "Could not send Email. Please check the EmailId" );
                se.printStackTrace ();
                return mapping.findForward ( "success" );
            }
            return ( mapping.findForward ( "sendAckMailView" ) );
        }
        else if ( "showContactPersonDetails".equalsIgnoreCase ( action ) )
        {
            try
            {
                String value = ( String ) session.getAttribute ( "ShowAgain" );
                if ( "True".equals ( value ) )
                {
                    contactPersons = ( ArrayList ) session.getAttribute ( "contactPersons" );
                }
                else
                {
                    contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );
                    String[]  externalUserEmails = SalesOrderDAO.loadEmailListForSalesOrderNotification();

                    int contactPersonsSize = 0;

                    if( externalUserEmails != null )
                    {
                        externalUserEmailsLength = externalUserEmails.length;
                    }
                    if( contactPersons != null )
                    {
                        contactPersonsSize = contactPersons.size();
                    }
                    ArrayList  userEmailsList = new ArrayList();
                    int userEmailsSize = 0;

                    try
                    {
                        userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_SALES_ORDERS);
                    }
                    catch( ScalarException se )
                    {
                        se.getRootCause().printStackTrace();
                        System.out.println( "Exception while retrieving email list");
                    }
                    if ( userEmailsList != null )
                    {
                        userEmailsSize = userEmailsList.size();
                    }
                    types = new String[ contactPersonsSize + externalUserEmailsLength + userEmailsSize + 2 ];

                    int i = 0;
                    for ( i = 0; i < contactPersonsSize; i++ )
                    {
                        ContactPerson contactPerson = ( ContactPerson ) contactPersons.get ( i );

                        if ( contactPerson.getSalesAckMail() )
                        {
                            contactPerson.setIsChecked ( true );
                        }
                        types[i] = "Contact Person";
                   }
                   int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( salesOrder.getCustomerId() );
                   String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();
                   String salesPersonEmail = CustomerDAO.getSalesPersonEmail(null, salesOrder.getSalesPerson(),salesOrder.getCustomerId());

                   if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                   {
                       ContactPerson customer = new ContactPerson();
                       customer.setContactPerson(salesOrder.getCustomerName());
                       customer.setEmail( customerEmail );
                       contactPersons.add(customer);
                       types[i++] = "Customer";
                   }
                   if ( salesPersonEmail != null && !"".equals(salesPersonEmail.trim()) )
                   {
                       ContactPerson salesPerson = new ContactPerson();
                       salesPerson.setContactPerson(salesOrder.getSalesPerson());
                       salesPerson.setEmail( salesPersonEmail );
                       salesPerson.setIsChecked ( true );
                       contactPersons.add(salesPerson);
                       types[i++] = "Sales Person";
                   }
                   ContactPerson externalUser[] = new ContactPerson[externalUserEmailsLength];
                   for (int j = 0; j < externalUserEmailsLength; j++) {
                        externalUser[j] = new ContactPerson();
                        externalUser[j].setEmail( externalUserEmails[j] );
                        externalUser[j].setIsChecked( true );
                        contactPersons.add(externalUser[j]);
                        types[i++] = "Notification";
                   }
                   if ( userEmailsList != null && userEmailsSize > 0 )
                    {
                       for( int j = 0; j < userEmailsSize; j++ )
                       {
                           ContactPerson customer = new ContactPerson();
                           StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                           String userName = st.nextToken ();
                           String userEmail = st.nextToken ();
                           customer.setContactPerson( userName );
                           customer.setEmail( userEmail );
                           customer.setIsChecked( true );
                           contactPersons.add(customer);
                           types[i++] = "User";
                       }
                    }
                   session.setAttribute ("types",types);
                }
            }
            catch ( ScalarException e )
            {
                e.printStackTrace ();
            }
            session.setAttribute ( "ShowAgain", "False" );
            request.setAttribute ( "contactPersons", contactPersons );

            return ( mapping.findForward ( "showContactPersons" ) );
        }
        else if ( "displayMailIds".equalsIgnoreCase ( action ) )
        {
            try
            {
                contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );

                int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( salesOrder.getCustomerId() );

                String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();
                String salesPersonEmail = CustomerDAO.getSalesPersonEmail(null, salesOrder.getSalesPerson(),salesOrder.getCustomerId());
                String[]  externalUserEmails = SalesOrderDAO.loadEmailListForSalesOrderNotification();
                ArrayList  userEmailsList = new ArrayList();
                int userEmailsSize = 0;

                try
                {
                    userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_SALES_ORDERS);
                }
                catch( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    System.out.println( "Exception while retrieving email list");
                }
                if ( userEmailsList != null )
                {
                    userEmailsSize = userEmailsList.size();
                }
                if( externalUserEmails != null )
                {
                    externalUserEmailsLength = externalUserEmails.length;
                }
                if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                {
                    ContactPerson customer = new ContactPerson();
                    customer.setContactPerson(salesOrder.getCustomerName());
                    customer.setEmail( customerEmail );
                    contactPersons.add(customer);
                }
                if ( salesPersonEmail != null && !"".equals(salesPersonEmail.trim()) )
                {
                    ContactPerson salesPerson = new ContactPerson();
                    salesPerson.setContactPerson(salesOrder.getSalesPerson());
                    salesPerson.setEmail( salesPersonEmail );
                    contactPersons.add(salesPerson);
                }
                ContactPerson externalUser[] = new ContactPerson[externalUserEmailsLength];
                for (int i = 0; i < externalUserEmailsLength; i++) {
                    externalUser[i] = new ContactPerson();
                    externalUser[i].setEmail( externalUserEmails[i] );
                    contactPersons.add(externalUser[i]);
                }
                if ( userEmailsList != null && userEmailsSize > 0 )
                {
                   for( int j = 0; j < userEmailsSize; j++ )
                   {
                       ContactPerson customer = new ContactPerson();
                       StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                       String userName = st.nextToken ();
                       String userEmail = st.nextToken ();
                       customer.setContactPerson( userName );
                       customer.setEmail( userEmail );
                       contactPersons.add(customer);
                   }
                }
                for ( int i = 0; i < contactPersons.size (); i++ )
                {
                    ContactPerson contactPerson = ( ContactPerson ) contactPersons.get ( i );
                    if ( request.getParameter ( "selectedValue" + i ) != null )
                    {
                        contactPerson.setIsChecked ( true );
                    }
                }

                session.setAttribute ( "contactPersons", contactPersons );
                session.setAttribute ( "ShowAgain", "True" );
            }
            catch ( Exception se )
            {
                System.out.println ( "Exception while loading sales order acknowledgement emails.. " );
            }
            return ( mapping.findForward ( "success" ) );
        }

        try
        {
            sendAckMailForm.setFromUser( ConfigManager.getFromEmailId(Constants.FROM_EMAIL_SALES_GROUP_NAME ) );
            subject = sendAckMailForm.getSubject ();
            ContactPerson cperson = null;
            if ( subject == null )
            {
                int orderType = request.getParameter("isSample") == null ? 1 : Integer.parseInt( request.getParameter("isSample") );
                if ( orderType == 0 )
                {
                    subject = customerName + " Sample SalesOrder Acknowledgement for "+ salesOrder.getSalesOrderNo();
                }
                else {
                    subject = customerName + " SalesOrder Acknowledgement for  " + customerPO;
                }
            }
            sendAckMailForm.setSubject ( subject );

            toUsers = sendAckMailForm.getToUsers();

            /*if( toUsers == null )
            {
                contactPersons = CustomerDAO.getAllContactPersonsWithEmails( null, salesOrder );

                String salesPersonEmail = CustomerDAO.getSalesPersonEmail( null, salesOrder.getSalesPerson(), salesOrder.getCustomerId() );

                String[] externalUserEmails = SalesOrderDAO.loadEmailListForSalesOrderNotification();

                ArrayList  userEmailsList = new ArrayList();
                int userEmailsSize = 0;
                try
                {
                    userEmailsList = UserDAO.loadEmailsByType( Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_SALES_ORDERS );
                }
                catch( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    System.out.println( "Exception while retrieving email list");
                }
                int contactPersonsSize = contactPersons.size ();
                if( externalUserEmails != null )
                {
                    externalUserEmailsLength = externalUserEmails.length;
                }
                if( userEmailsList != null )
                {
                   userEmailsSize = userEmailsList.size();
                }
                String [] mailTo =new String[ contactPersonsSize + externalUserEmailsLength + userEmailsSize + 2 ];
                int i = 0;
                int j = 0;
                int k = 0;
                for ( i = 0; i < contactPersonsSize ; i++ )
                {
                   cperson = ( ContactPerson ) contactPersons.get ( i );
                   if(cperson.getSalesAckMail())
                   {
                        mailTo[ i ] = cperson.getEmail();
                   }
                }
                for ( j = 0; j < externalUserEmailsLength; j++)
                {
                    mailTo[ i + j ] = externalUserEmails[ j ];
                }
                for ( k = 0; k < userEmailsSize; k++)
                {
                    StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(k), "/" );
                    String userName = st.nextToken ();
                    String userEmail = st.nextToken ();
                    mailTo[ i + j + k ] = userEmail;
                }
                if ( salesPersonEmail != null && !"".equals( salesPersonEmail ) )
                {
                    mailTo[ i + j + k + 1 ] = salesPersonEmail;
                }
                
                sendAckMailForm.setToUsers( mailTo );
            }*/

            if( toUsers == null )
            {
                sendAckMailForm.setToUsers( UserDAO.loadAllApproversEmails( null, -1, "SalesOrder" ) );
            }
        }

        catch ( Exception se )
        {
            System.out.println ( "Exception while loading sales order acknowledgement emails.. "+se );
        }
        session.removeAttribute ( "ShowAgain" );
        session.removeAttribute ( "isConfirm" );
        sendAckMailForm.setCustomerId ( salesOrder.getCustomerId () );
        request.setAttribute ( "sendAckMailForm", sendAckMailForm );
        return ( mapping.findForward ( "success" ) );
    }
}